<?php

namespace app\common\controller;

use app\common\library\Auth;
use think\Config;
use think\Controller;
use think\Hook;
use think\Lang;
use think\Db;
use think\Request;
use think\Response;
use think\exception\HttpResponseException;

/**
 * 前台控制器基类
 */
class Frontend extends Controller {

    /**
     * 布局模板
     * @var string
     */
    protected $layout = '';
    protected $iUserId = 0; //用户ID
    protected $userBoxId = 0; //用户盒子ID
    /**
     * 默认响应输出类型,支持json/xml
     * @var string 
     */
    protected $responseType = 'json';

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    public function _initialize() {
//        Session('user_id', 45);
//        Session('user_box_id', 41);
        $this->iUserId = Session('user_id');
        $this->userBoxId = Session('user_box_id');
        //如果未登录 跳到微信登录
        $appid = 'wxc9abd79c9ddd15e3';
        if (empty($this->iUserId) || $this->iUserId == 0) {
            $redirect_uri = 'https://www.mohebianli.com' . url('Pub/auth');
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            header('Location: ' . $url);
        } else {
            $user_info = Db::name('users')->where(['user_id' => $this->iUserId])->find();

            if (empty($user_info)) {
                $redirect_uri = 'https://www.mohebianli.com' . url('Pub/auth');
                $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                header('Location: ' . $url);
                return;
            }

            if ($this->userBoxId) {
                $is_bind_phone = db('configure')->where(['key' => 'bangdingshoujihao'])->value('desc');
                if ($is_bind_phone == 1) {
                    //判断是否绑定手机号
                    if (empty($user_info['phone'])) {
                        $this->redirect('https://www.mohebianli.com' . url('Pub/bindphone'));
                    }
                }
            }

            $is_shiming = db('configure')->where(['key' => 'shimingrenzhen'])->value('desc');
            if ($is_shiming == 1) {
                //判断是否实名认证
                if (empty($user_info['identity_number'])) {
                    $this->redirect('https://www.mohebianli.com' . url('Pub/userAuth'));
                }
            }

            //判断是否审核通过
            if ($user_info['user_status'] != 1) {
                $this->redirect('https://www.mohebianli.com' . url('Pub/userStatus'));
            }

            //判断是否禁用
            if ($user_info['status'] == 1) {
                $this->redirect('https://www.mohebianli.com' . url('Pub/disable'));
            }

            $pv['page'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $pv['user_id'] = $this->iUserId;
            $pv['user_box_id'] = $this->userBoxId;

            db('page_view')->insert($pv);

            $is_exis = db('user_view')->where('createtime', '>=', date('Y-m-d'))->where('user_id', $this->iUserId)->find();
            if (empty($is_exis)) {
                $uv['user_id'] = $this->iUserId;
                $uv['user_box_id'] = $this->userBoxId;
                db('user_view')->insert($uv);
            }
        }

        $info = db('configure')->where('key', 'fenxiang')->find();
        $info = json_decode($info['desc'], true);

        $user_box_id = Session('user_box_id');
        $box_no = db('user_box')->where('user_box_id', $user_box_id)->value('box_no');
        $share_url = 'https://www.mohebianli.com/index/pub/index/box/' . base64_encode($box_no);
        $this->assign('user_box_id', $this->userBoxId);
        $this->assign('share_url', $share_url);
        $this->assign('data', $info);
    }

    /**
     * 操作成功返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param int   $code   错误码，默认为1
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = []) {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param int   $code   错误码，默认为0
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = []) {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = []) {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

}
